//
//  ShareViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/27.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ShareViewController.h"

#import "MoreDetailViewController.h"
#import "ChanelDetailViewController.h"
#import "GameDetailViewController.h"
#import "DesignerDetailViewController.h"

#import "ChannelTableViewCell.h"
#import "FoundListCell.h"
#import "ChannelDetailCell.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ShareViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *moveLine;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) NSInteger currentType;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) NSMutableArray *currentPageArr;
@property (nonatomic, strong) NSMutableArray *pagesArr;

@property (nonatomic,strong)  UIButton *noteBtn;

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerViewController  *playerView;

@end

@implementation ShareViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"分享";
    self.currentType = 0;
    self.dataArray = @[[NSMutableArray array],[NSMutableArray array],[NSMutableArray array],[NSMutableArray array]];
    self.currentPageArr = [NSMutableArray arrayWithArray:@[@"1",@"1",@"1",@"1"]];
    self.pagesArr = [NSMutableArray arrayWithArray:@[@"1",@"1",@"1",@"1"]];
    [self setTopBar];
    [self setUI];
    
    _noteBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(79), ScreenX375(27))];
    [_noteBtn setTitleColor:REXADECIMALCOLOR(@"#f21934") forState:UIControlStateNormal];
    _noteBtn.titleLabel.font = Kfont(14);
    _noteBtn.layer.cornerRadius = ScreenX375(13.5);
    _noteBtn.layer.borderColor = REXADECIMALCOLOR(@"#f21934").CGColor;
    _noteBtn.layer.borderWidth = 1;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_noteBtn];
}

- (void)setTopBar {
    UIView *topBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(35))];
    topBar.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    [self.view addSubview:topBar];
    
    NSArray *nameArr = @[@"设计师",@"频道",@"轮播图",@"作品"];
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *typeBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * ScreenX375(69) + (SCREEN_WIDTH - ScreenX375(276)) / 2, 0, ScreenX375(69), ScreenX375(35))];
        [typeBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        [typeBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
        [typeBtn setTitleColor:REXADECIMALCOLOR(@"#f21934") forState:UIControlStateSelected];
        typeBtn.titleLabel.font = Kfont(13);
        typeBtn.tag = 100 + i;
        if (i == 0) {
            typeBtn.selected = YES;
            _selectBtn = typeBtn;
        }
        [typeBtn addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
        [topBar addSubview:typeBtn];
    }
    
    self.moveLine = [[UIView alloc] initWithFrame:CGRectMake((ScreenX375(69) - ScreenX375(40)) / 2 + (SCREEN_WIDTH - ScreenX375(276)) / 2, ScreenX375(35) - 2, ScreenX375(40), 2)];
    self.moveLine.backgroundColor = REXADECIMALCOLOR(@"#f21934");
    [topBar addSubview:self.moveLine];
}

- (void)typeClick:(UIButton *)button {
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    self.currentType = button.tag - 100;
    BaseTableView *tableView = [self.view viewWithTag:100 + button.tag];
    [tableView.mj_header beginRefreshing];
    [UIView animateWithDuration:0.3 animations:^{
        self.moveLine.frame = CGRectMake((ScreenX375(69) - ScreenX375(40)) / 2 + (SCREEN_WIDTH - ScreenX375(276)) / 2 + (button.tag - 100) * ScreenX375(69), ScreenX375(35) - 2, ScreenX375(40), 2);
    }];
    [_scrollView setContentOffset:CGPointMake((button.tag - 100) * SCREEN_WIDTH, 0) animated:YES];
}

- (void)setUI {
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, ScreenX375(35), SCREEN_WIDTH, SCREEN_HEIGHT - ScreenX375(35))];
    _scrollView.showsVerticalScrollIndicator = false;
    _scrollView.showsHorizontalScrollIndicator = false;
    _scrollView.pagingEnabled = true;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 4, 0);
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < 4; i++) {
        BaseTableView *tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(35))];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.tag = 200 + i;
        if (i == 0) {
            tableView.rowHeight = ScreenX375(430);
        }else if (i == 1) {
            tableView.rowHeight = ScreenX375(430);
        }else if (i == 2) {
            tableView.rowHeight = ScreenX375(184);
        }else {
            tableView.rowHeight = ScreenX375(340);
        }
        [_scrollView addSubview:tableView];
        
        __weak __typeof(self)weakSelf = self;
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf.currentPageArr replaceObjectAtIndex:weakSelf.currentType withObject:@"1"];
            
            NSArray *urlArr = @[@"api/shareUserList",@"api/shareChannelList",@"api/shareSowing",@"api/shareProList"];
            NSString *url = [NSString stringWithFormat:@"%@%@",REQUESTHEADER,urlArr[weakSelf.currentType]];
            NSDictionary *dict = @{@"userId":kNSUDefaultReadKey(@"userId"),@"page":@"1"};
            
            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    [tableView.mj_header endRefreshing];
                    NSError *error;
                    [weakSelf.dataArray[weakSelf.currentType] removeAllObjects];
                    [weakSelf.pagesArr replaceObjectAtIndex:weakSelf.currentType withObject:[NSString stringWithFormat:@"%@",successResponse[@"data"][@"pages"]]];
                    if ([weakSelf.currentPageArr[weakSelf.currentType] isEqualToString:weakSelf.pagesArr[weakSelf.currentType]]) {
                        tableView.mj_footer.hidden = YES;
                    }
                    if (weakSelf.currentType == 1) {
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            ChannelModel *model = [[ChannelModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.currentType] addObject:model];
                        }
                        
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@频道",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }else if (weakSelf.currentType == 0){
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            FoundModel *model = [[FoundModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.currentType] addObject:model];
                        }
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@设计师",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }else if (weakSelf.currentType == 3){
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            ChannelListModel *model = [[ChannelListModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.currentType] addObject:model];
                        }
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@作品",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }else {
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            [weakSelf.dataArray[weakSelf.currentType] addObject:dic];
                        }
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@轮播图",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_header endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            NSInteger currentPage = [weakSelf.currentPageArr[weakSelf.currentType] integerValue];
            [weakSelf.currentPageArr replaceObjectAtIndex:weakSelf.currentType withObject:[NSString stringWithFormat:@"%ld",currentPage++]];
            
            NSArray *urlArr = @[@"api/shareUserList",@"api/shareChannelList",@"api/shareSowing",@"api/shareProList"];
            NSString *url = [NSString stringWithFormat:@"%@%@",REQUESTHEADER,urlArr[weakSelf.currentType]];
            NSDictionary *dict = @{@"userId":kNSUDefaultReadKey(@"userId"),@"page":weakSelf.currentPageArr[weakSelf.currentType]};

            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    [tableView.mj_footer endRefreshing];
                    NSError *error;
                    if ([weakSelf.currentPageArr[weakSelf.currentType] isEqualToString:weakSelf.pagesArr[weakSelf.currentType]]) {
                        tableView.mj_footer.hidden = YES;
                    }
                    if (weakSelf.currentType == 1) {
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            ChannelModel *model = [[ChannelModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.currentType] addObject:model];
                        }
                        
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@频道",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }else if (weakSelf.currentType == 0){
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            FoundModel *model = [[FoundModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.currentType] addObject:model];
                        }
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@设计师",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }else if (weakSelf.currentType == 3){
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            ChannelListModel *model = [[ChannelListModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.dataArray[weakSelf.currentType] addObject:model];
                        }
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@作品",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_footer endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        if (i == 0) {
            [tableView.mj_header beginRefreshing];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dataArray[tableView.tag - 200] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 200) {
        FoundListCell *cell = [FoundListCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.foundModel = _dataArray[0][indexPath.row];
        return cell;
    }else if (tableView.tag == 201) {
        ChannelTableViewCell *cell = [ChannelTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.channelModel = _dataArray[1][indexPath.row];
        return cell;
    }else if (tableView.tag == 202) {
        static NSString *cellId = @"imageCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(19), ScreenX375(10), SCREEN_WIDTH - ScreenX375(38), ScreenX375(164))];
        [imageView sd_setImageWithURL:[NSURL URLWithString:_dataArray[2][indexPath.row][@"pic"]] placeholderImage:nil options:SDWebImageRetryFailed];
        imageView.layer.cornerRadius = ScreenX375(8);
        imageView.layer.masksToBounds = YES;
        [cell addSubview:imageView];
        return cell;
    }else {
        ChannelDetailCell *cell = [ChannelDetailCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.channelListModel = _dataArray[3][indexPath.row];
        ChannelListModel *model = _dataArray[3][indexPath.row];
        cell.appraiseClick = ^{
            MoreDetailViewController *vc = [[MoreDetailViewController alloc] init];
            vc.proId = model.Id;
            [self.navigationController pushViewController:vc animated:YES];
        };
        cell.commentClick = ^{
            MoreDetailViewController *vc = [[MoreDetailViewController alloc] init];
            vc.proId = model.Id;
            [self.navigationController pushViewController:vc animated:YES];
        };
        cell.shareClick = ^{
            MoreDetailViewController *vc = [[MoreDetailViewController alloc] init];
            vc.proId = model.Id;
            [self.navigationController pushViewController:vc animated:YES];
        };
        cell.playClick = ^{
            [self playVideoWithUrl:model.pic];
        };
        return cell;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        [UIView animateWithDuration:0.3 animations:^{
            self.moveLine.frame = CGRectMake((ScreenX375(69) - ScreenX375(40)) / 2 + (SCREEN_WIDTH - ScreenX375(276)) / 2 + (button.tag - 100) * ScreenX375(69), ScreenX375(35) - 2, ScreenX375(40), 2);
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        self.currentType = index;
        BaseTableView *tableView = [self.view viewWithTag:200 + index];
        [tableView.mj_header beginRefreshing];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 200) {
        FoundModel *model = _dataArray[0][indexPath.row];
        DesignerDetailViewController *vc = [[DesignerDetailViewController alloc] init];
        vc.designerId = model.userId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (tableView.tag == 201) {
        ChannelModel *model = _dataArray[1][indexPath.row];
        ChanelDetailViewController *vc = [[ChanelDetailViewController alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (tableView.tag == 203) {
        ChannelListModel *model = _dataArray[3][indexPath.row];
        MoreDetailViewController *vc = [[MoreDetailViewController alloc] init];
        vc.proId = model.Id;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (tableView.tag == 202) {
        NSDictionary *dic = _dataArray[2][indexPath.row];
        GameDetailViewController *vc = [[GameDetailViewController alloc] init];
        vc.proDic = dic;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)playVideoWithUrl:(NSString *)url {
    NSString *playString = url;
    //视频播放的url
    NSURL *playerURL = [NSURL URLWithString:playString];
    //初始化
    self.playerView = [[AVPlayerViewController alloc]init];
    //AVPlayerItem 视频的一些信息  创建AVPlayer使用的
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:playerURL];
    //通过AVPlayerItem创建AVPlayer
    self.player = [[AVPlayer alloc]initWithPlayerItem:item];
    //给AVPlayer一个播放的layer层
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    layer.frame = CGRectMake(0, 100, self.view.frame.size.width, 200);
    layer.backgroundColor = [UIColor greenColor].CGColor;
    //设置AVPlayer的填充模式
    layer.videoGravity = AVLayerVideoGravityResize;
    //设置AVPlayerViewController内部的AVPlayer为刚创建的AVPlayer
    self.playerView.player = self.player;
    //关闭AVPlayerViewController内部的约束
    self.playerView.view.translatesAutoresizingMaskIntoConstraints = YES;
    [self presentViewController:self.playerView animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
